<template>
	<view class="y-flex y-flex-1">
		<module-list
		ref="list"
		:component="components"
		:cell="cell"
		:comment="comments"
		:bounce="pageStyle.enableBounce"
		:back-top-show="pageStyle.enableBackTop"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:loadmoreable="pageStyle.enableLoadmore == 1"
		:loadingColor="pageStyle.loadingColor"
		:backTopImage="pageStyle.backTopImage"
		:params="detail"
		@scroll="handleScroll"
		@pulldown="handlePulldown"
		@loaded="handleModuleLoaded">
			<template #top v-if="detail && detail.uniqueId">
				<cell v-if="detail && detail.title">
					<find-detail ref="detail"
					:data="detail"
					:options="detailOptions"
					:bg-color="componentStyle['background-color']"
					:style="componentStyle"
					@utils="handleUtils"
					@startClick="handleStartClick"
					@continueClick="handleContinueClick"></find-detail>
				</cell>
				<cell v-if="items && items.length > 0">
					<find-items :data="items" :options="itemOptions" :style="componentStyle" @moreClick="handleMoreClick" @itemClick="handleItemClick"></find-items>
				</cell>
			</template>
		</module-list>
	</view>
</template>

<script>
	import ModuleList from '../components/ModuleList.vue'
	import FindDetail from '../components/FindModule/FindDetail.vue'
	import FindItems from '../components/FindModule/FindItems.vue'
	import { pixelunit, randomId, hexToRgba } from '@/assets/js/util.js'
	export default {
		inject: ['getSkinColor', 'getPage', 'getComponentStyle', 'getPageStyle', 'getQuery', 'actionSheet', 'showItems', 'showAudioPlayer'],
		components: {
			ModuleList,
			FindDetail,
			FindItems
		},
		computed: {
			skinColor () {
				return this.getSkinColor()
			},
			//路由参数
			query () {
				return this.getQuery()
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			components () {
				return this.page?.components || []
			},
			cell () {
				return this.page?.cell || {}
			},
			comments () {
				return this.page?.comments || {}
			},
			componentStyle () {
				const style = this.getComponentStyle()
				return {
					'margin-top': pixelunit(style.marginTop),
					'margin-bottom': pixelunit(style.marginBottom),
					'margin-left': pixelunit(style.marginLeft),
					'margin-right': pixelunit(style.marginRight),
					'background-color': hexToRgba(style.backgroundColor, style.backgroundOpacity),
					'border-radius': pixelunit(style.borderRadius)
				}
			},
			detailOptions () {
				return {
					startText: '开始播放',
					continueText: '继续播放',
					recordText: '播放记录'
				}
			},
			itemOptions () {
				return {
					title: '播放列表',
					unit: "首"
				}
			},
			network () {
				return this.$store.getters['network/GET']
			},
			actionItem () {
				return this.items.length > 0 ? this.items[this.actionIndex] : {}
			},
			pixelunit () {
				return pixelunit
			}
		},
		data () {
			return {
				detail: {},//详情信息
				items: [],//分集列表
				current: 0,//当前播放索引
				actionIndex: 0//操作歌曲
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		methods: {
			onShow () {
				this.$refs.detail && this.$refs.detail.getRecord()
			},
			handleUtils (e) {
				this.$emit('utils', e)
			},
			handleStartClick () {
				this.playmusic(0)
			},
			handleContinueClick (record) {
				this.playmusic(record.current || 0, record.position || 0)
			},
			handleMoreClick () {
				const record = this.$refs.detail.record
				this.showItems({
					title: '选曲',
					data: this.items,
					current: record.current,
					defaultTitle: this.detail.title,
					unit: '集',
					success: res => {
						if ( res.confirm ) {
							this.playmusic(res.current)
						}
					}
				})
			},
			handleItemClick (e) {
				this.playmusic(e.index)
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			playmusic (current, start) {
				this.actionIndex = current
				if ( this.$store.getters['audio/GET_CURRENT_SRC'] ) {//正在播放歌曲
					this.actionSheet({
						title: this.actionItem.title || this.detail.title + '第' + (this.actionIndex + 1) + '首',
						data: ['替换歌曲列表', '插入歌曲列表', '插入单曲', '插入并播放单曲'],
						success: res => {
							if ( res.confirm ) {
								this.playmusicComfirm(res.current)
							}
						}
					})
				} else {
					this.playmusicComfirm(0)
				}
			},
			playmusicComfirm (action) {
				const list = this.items.map(item => {
					return {
							query: this.query,
							detail: this.detail,
							item,
							current: this.actionIndex,//当前播放列表index索引
							audioId: randomId(),
							context: this.page?.context || {},
							lyrics: this.page?.lyrics || {}
						}
					}
				)
				if ( [0, 1].includes(action) ) {
					if ( action == 0 ) {
						const item = list[this.actionIndex]
						this.$store.dispatch('audio/replace', list)
						this.$nextTick(function () {
							this.$store.dispatch('audio/change', item.audioId)
							this.showAudioPlayer()
						})
					} else this.$store.dispatch('audio/insert', list)
				} else if ( [2, 3].includes(action) ) {
					const item = list[this.actionIndex]
					this.$store.dispatch('audio/save', item)
					if ( action == 3 ) {
						this.$store.dispatch('audio/change', item.audioId)
						this.showAudioPlayer()
					}
				}
			},
			handleModuleLoaded () {
				this.$emit('loaded', true)
				this.$refs.list && this.$refs.list.pulldownSuccess()
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.items = await this.handleGetItems()
					this.$nextTick(function () {
						this.$refs.list && this.$refs.list.initModule(callback)
						this.$refs.detail && this.$refs.detail.getRecord()
					})
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = await this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetItems () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? await this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
				}
				return staticData.concat(data).map(s => Object.assign({}, s, { loading: false, isLive: s.isLive == 1 ? true : s.isLive == 0 ? false : s.isLive }))
			}
		}
	}
</script>

<style>
</style>